/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pkgUtil.pkgFrameworkXML.pkgSupport;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
import pkgUtil.pkgFrameworkXML.pkgEntity.WXmlObject;


/**
 *
 * @author Administrador
 */
public class HelperWriteXml {

    private WXmlObject xmlObject;
    private Document xmlDocument;

    public HelperWriteXml(WXmlObject xmlObject) throws XmlWriterException {
        validateXmlObject(xmlObject);
        this.xmlObject = xmlObject;
    }

    private void validateXmlObject(WXmlObject xmlObject) throws XmlWriterException {
        if (xmlObject == null) {
            throw new XmlWriterException("XmlObject is null");
        }
        if (xmlObject.getFileXml() == null) {
            throw new XmlWriterException("Path file Xml is null");
        }

        if (xmlObject.getFileXml().trim().length() == 0) {
            throw new XmlWriterException("Path file Xml is not valid");
        }

        if (xmlObject.getRoot() == null) {
            throw new XmlWriterException("Root Xml is null");
        }
    }

    public Element buildElement(String name, String value) throws XmlWriterException {
        if (name == null) {
            throw new XmlWriterException("Name is null");
        }
        Element e = new Element(name);
        if (value != null) {
            e.setText(value);
        }
        return e;
    }

    public Element addChildToRoot(String nameChild) {
        Element child = new Element(nameChild);
        xmlObject.getRoot().addContent(child);
        return child;
    }

    public void addChildToRoot(Element child) {
        xmlObject.getRoot().addContent(child);
    }

    public void addChildToElement(Element parent, Element child) {
        parent.addContent(child);
    }

    public Document buildXml() throws FileNotFoundException, IOException {

        FileOutputStream file_os = null;
        try {
            xmlDocument = new Document();
            xmlDocument.addContent(xmlObject.getRoot());
            XMLOutputter xml_out = new XMLOutputter();
            file_os = new FileOutputStream(xmlObject.getFileXml());
            xml_out.output(xmlDocument, file_os);

        } finally {
            if (file_os != null) {
                file_os.close();
            }
        }

        return xmlDocument;

    }
}
